package middleware

import (
	"encoding/gob"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type LoginMiddlewareBuilder struct {
}

func NewLoginMiddlewareBuilder() *LoginMiddlewareBuilder {
	return &LoginMiddlewareBuilder{}
}
func (l *LoginMiddlewareBuilder) CheckLogin() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(context *gin.Context) {
		path := context.Request.URL.Path
		if path == "/users/login" || path == "/users/signup" ||
			path == "/users/login_sms/code/send" || path == "/users/login_sms" {
			return
		}
		//session取值
		sess := sessions.Default(context)
		sess.Options(sessions.Options{
			//Secure:   true,
			//HttpOnly: true,
			MaxAge: 60, //当会话的最大存活时间过期后，用户将需要重新进行身份验证或重新创建会话
		})
		id := sess.Get("userId")
		if id == nil {
			context.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		now := time.Now()
		//每分钟内第一次访问我都刷新
		const updateTimeKey = "update_time"
		val := sess.Get(updateTimeKey)
		lastUpdateTime, ok := val.(time.Time)
		if val == nil || !ok || now.Sub(lastUpdateTime) > time.Second*10 {
			//你第一次进来,设置过期时间
			sess.Set(updateTimeKey, now)
			sess.Set("userId", id)
			if err := sess.Save(); err != nil {
				fmt.Println(err)
			}
		}
	}
}
